use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{self, Read};

/// 从 `district.json` 文件读取并解析数据
fn read_district_data() -> Result<HashMap<String, HashMap<String, Vec<String>>>, io::Error> {
    let mut file = File::open("topic1/solutiont2/district.json")?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    print!("{:?}",content);
    let mut district_data = HashMap::new();
    let mut current_batch = String::new();
    let mut current_group = HashMap::new();

    for line in content.lines() {
        if line.trim().ends_with(":") {
            // 保存当前批次数据
            if !current_batch.is_empty() && !current_group.is_empty() {
                district_data.insert(current_batch.clone(), current_group);
                current_group = HashMap::new();
            }
            // 记录新批次的键
            current_batch = line.trim_end_matches(':').to_string();
        } else if let Some((city, connections)) = line.split_once(':') {
            let city = city.trim().trim_matches('"').to_string();
            let connections: Vec<String> = connections
                .split(',')
                .map(|c| c.trim().trim_matches('"').to_string())
                .collect();
            current_group.insert(city, connections);
        }
    }

    // 保存最后一个批次
    if !current_batch.is_empty() && !current_group.is_empty() {
        district_data.insert(current_batch, current_group);
    }

    Ok(district_data)
}

/// 计算每个批次的省份数
pub fn count_provinces() -> String {
    let district_data = match read_district_data() {
        Ok(data) => data,
        Err(_) => return "Error reading district.json".to_string(),
    };
    println!("{:?}", district_data);
    let mut results = Vec::new();

    for (_, batch) in district_data {
        let mut visited = HashSet::new();
        let mut province_count = 0;

        for city in batch.keys() {
            if !visited.contains(city) {
                dfs(city, &batch, &mut visited);
                province_count += 1;
            }
        }

        results.push(province_count.to_string());
    }

    results.join(",")
}

/// 深度优先搜索（DFS），标记连通城市
fn dfs(city: &str, batch: &HashMap<String, Vec<String>>, visited: &mut HashSet<String>) {
    if visited.contains(city) {
        return;
    }
    visited.insert(city.to_string());
    if let Some(neighbors) = batch.get(city) {
        for neighbor in neighbors {
            dfs(neighbor, batch, visited);
        }
    }
}